package com.hxwm.hwdbtool.util;

import com.hxwm.hwdbtool.entity.dbconnect.HwDateSource;
import javafx.scene.control.Alert;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @program: hwdbtool
 * @ClassName JavaFXUIControlUtil
 * @description:
 * @author: hxwm
 * @create: 2024-04-27 18:21
 * @Version 1.0
 **/
public class JavaFXUIControlUtil {


    /**
     * 数据库连接测试
     * @param url
     * @param user
     * @param password
     */
    public static void testDatabaseConnection(String url, String user, String password) {
        try {
            String dbType = url.split(":")[1];
            if("db2".equals(dbType)) {
                Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
            }else if("mysql".equals(dbType)){
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            }else if("oracle".equals(dbType)){
                Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            }
            // 尝试连接数据库
            Connection connection = DriverManager.getConnection(url, user, password);
            // 如果成功，显示连接成功的消息
            showInformationDialog("连接测试","连接成功");
            // 关闭连接
            connection.close();
        } catch (Exception ex) {
            // 如果失败，显示错误消息
            showInformationDialog("连接测试","连接失败");
        }
    }

    /**
     * 数据库连接测试
     * @param hwDateSource
     * @return
     */
    public static Boolean testDatabaseConnection(HwDateSource hwDateSource) {
        try {
            String dbType = hwDateSource.getDriverType();
            if("db2".equals(dbType)) {
                Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
            }else if("mysql".equals(dbType)){
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            }else if("oracle".equals(dbType)){
                Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            }
            // 尝试连接数据库
            Connection connection = DriverManager.getConnection(hwDateSource.getDbUrl(), hwDateSource.getDbUser(), hwDateSource.getDbPassword());
            // 关闭连接
            connection.close();
            return true;
        } catch (Exception ex) {
            // 如果失败，显示错误消息
            return false;
        }
    }
    /**
     * 提示框
     * @param title
     * @param message
     */
    public static void showInformationDialog(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }


}